package com.shuma.userservice.mq;

import com.shuma.common.config.LogMqConfig;
import com.shuma.common.event.OperationLogEvent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
@RequiredArgsConstructor
@Slf4j
public class LogMessageSender {
    private final RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init() {
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if (ack) {
                log.info("消息成功发送到Broker");
            } else {
                log.error("消息发送失败，原因：{}", cause);
            }
        });
    }

    public void send(OperationLogEvent event) {
        rabbitTemplate.convertAndSend(LogMqConfig.EXCHANGE, LogMqConfig.ROUTING_KEY, event, message -> {
            message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
            return message;
        });
    }
}
